﻿using System.IO;
using System.Threading;
using Synology.DS.Common;
using Synology.DS.Interface.Abstract;

namespace Synology.DS.Core
{
	public class TorrentsWatcher : ITorrentsWatcher
	{
		private readonly IConfigurationManager _config;
		private Timer _timer;
		private object _locker = new object();

		public TorrentsWatcher(IConfigurationManager config)
		{
			_config = config;
		}

		public void Start()
		{
			Log.Info("[Directory]: '{0}'", _config.TorrentFilesFolder);
			Log.Info("[Filter]: '{0}'", string.IsNullOrEmpty(_config.TorrentFilesFilter) ? "<empty>" : _config.TorrentFilesFilter);

			if (!Directory.Exists(_config.TorrentFilesFolder))
				throw new DirectoryNotFoundException(string.Format("'{0}' directory doesn't exist", _config.TorrentFilesFolder));

			_timer = new Timer(x => ProcessDirectoryFiles(), null, 0, Const.WatchTimerInterval);
		}

		public void Stop()
		{
			if (_timer != null)
				_timer.Dispose();
		}

		public event NewTorrentEventHandler NewTorrent;
		private void RaiseNewTorrent(string filePath)
		{
			Log.Info("New torrent file available: '{0}'", filePath);
			if (NewTorrent != null)
				NewTorrent(this, new NewTorrentEventArgs(filePath));
		}

		private void ProcessDirectoryFiles()
		{
			lock (_locker)
			{
				var files = Directory.GetFiles(_config.TorrentFilesFolder, _config.TorrentFilesFilter, SearchOption.TopDirectoryOnly);
				foreach (string file in files)
				{
					RaiseNewTorrent(file);
				}
			}
		}
	}
}
